import Global from "./Global";

const {ccclass, property} = cc._decorator;

@ccclass
export default class PlayerController extends cc.Component {

    @property(cc.Node)
    player: cc.Node = null;
    @property(cc.Label)
    locationLbl: cc.Label = null;

    playerSpeed: number = Global.velocityIterations;

    rigidBody: cc.RigidBody = null;

    isTouch: boolean = false;

    movePosition: cc.Vec2 = null;

    direction: cc.Vec2 = null;

    vec2Zero: cc.Vec2 = new cc.Vec2();

    onLoad () {
       if (this.player) {
           this.rigidBody = this.player.getComponent(cc.RigidBody);
           this.rigidBody.linearVelocity = new cc.Vec2(0,-100);
       }

       this.registerTouchEvent();

    }

    private registerTouchEvent () {
        let canvas = cc.find('Canvas');
        canvas.on(cc.Node.EventType.TOUCH_START,(event: cc.Event.EventTouch) => {
            let touchLoc:cc.Vec2 = event.getLocation();
            this.isTouch = true;
            this.movePosition = this.player.parent.convertToNodeSpaceAR(touchLoc);
            if (this.locationLbl) {
                this.locationLbl.string = '点击坐标: x ' + Math.floor(touchLoc.x) + "y " + Math.floor(touchLoc.y);
            }
        },this.node);

        canvas.on(cc.Node.EventType.TOUCH_MOVE,(event: cc.Event.EventTouch) => {
            let touchLoc:cc.Vec2 = event.getLocation();
            this.movePosition = this.player.parent.convertToNodeSpaceAR(touchLoc);
            if (this.locationLbl) {
                this.locationLbl.string = '点击坐标: x ' + Math.floor(touchLoc.x) + "y " + Math.floor(touchLoc.y);
            }
        },this.node);


        canvas.on(cc.Node.EventType.TOUCH_END,(event: cc.Event.EventTouch) => {
            this.isTouch = false;
        },this.node);
    }

    update (dt) {
        //this.player.getComponent(cc.MotionStreak)._onNodePositionChanged();
        let oldPostion: cc.Vec2 = this.player.position;
        if (!this.isTouch) {
            //return;
            if (!this.direction) {
                this.direction = cc.pNormalize(cc.pSub(this.switchDirection(),oldPostion));
            }
        }else {
            this.direction = cc.pNormalize(cc.pSub(this.movePosition,oldPostion));
        }
        this.rigidBody.linearVelocity = this.vec2Zero;
        //let newPosition = cc.pAdd(oldPostion,cc.pMult(this.direction,this.playerSpeed));

        //this.player.setPosition(newPosition);
        this.rigidBody.linearVelocity = cc.pMult(this.direction,this.playerSpeed);

    }

    switchDirection (): cc.Vec2 {
        //随机四个方向
        //let randomNum
        return new cc.Vec2(this.player.position.x + 100, this.player.position.y);
    }

}
